import React, { useEffect, useState } from "react";
import ReactMarkdown from "react-markdown/with-html";
import marked, { Tokenizer } from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import { useHistory, useLocation } from "react-router-dom";
import style from "./style.module.css";
import { FrownOutlined } from "@ant-design/icons";
import { Button } from "antd";

const ContendDetail = () => {
  const [content, setContent] = useState("");
  const [empty, setEmpty] = useState(false);
  const history = useHistory();

  const { pathname, origin, hash } = window.location;
  useEffect(() => {
    const mdUrl = hash.slice(9, hash.length);
    const temp = mdUrl.split("-");
    const url = `./md/${temp[0]}/${temp[1]}.md`;
    changeCurrentArticle(url);
  }, []);
  // 更改当前文档
  const changeCurrentArticle = async (url: string) => {
    const res = await fetch(url);

    if (res.status === 404) {
      setEmpty(true);
      return;
    }
    const content = await res.text();
    marked.setOptions({
      renderer: new marked.Renderer(),
      baseUrl: `${origin}${pathname}`,
      gfm: true,
      breaks: true,
      pedantic: false,
      smartLists: true,
      smartypants: true,
      langPrefix: "language1-",
      highlight(code) {
        return hljs.highlightAuto(code).value;
      },
    });
    setContent(content ? marked(content) : "");
  };
  return (
    <div>
      <Button type="dashed" onClick={() => history.goBack()}>
        回退
      </Button>
      <div
        className="article-detail"
        dangerouslySetInnerHTML={{
          __html: content || "",
        }}
      />
      {empty && (
        <div className={style.isEmpty}>
          {" "}
          <FrownOutlined /> 您访问的资源不存在{" "}
          <Button type="dashed" onClick={() => history.goBack()}>
            返回
          </Button>
        </div>
      )}
    </div>
  );
};

export default ContendDetail;
